//
//  collectedDataDetailView.m
//  dataGathering
//
//  Created by apple on 14/12/16.
//  Copyright (c) 2014年 shuili. All rights reserved.
//

#import <AVFoundation/AVFoundation.h>
#import "collectedDataDetailView.h"

#import "UIImageView+click.h"

@interface collectedDataDetailView ()
@property (weak, nonatomic) IBOutlet UILabel *typeLabel;
@property (weak, nonatomic) IBOutlet UILabel *idLabel;
@property (weak, nonatomic) IBOutlet UITextField *dataNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *dataDescriptionTextField;
@property (weak, nonatomic) IBOutlet UILabel *dataCollectedTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *dataUserNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *dataRealNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *sameNameAlertLabel;
@property (weak, nonatomic) IBOutlet UIScrollView *imageScrollView;

@property(nonatomic, retain)UIButton *addImageButton;
@property(nonatomic, retain)NSMutableArray *imageArray;
@property(nonatomic, retain)NSMutableArray *imageViewArray;
@end

@implementation collectedDataDetailView

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    NSLog(@"name is %@", [_currentData name]);
    [_typeLabel setText:[_currentData type]];
    [_idLabel setText:[_currentData idNumber]];
    [_dataNameTextField setText:[_currentData name]];
    [_dataDescriptionTextField setText:[_currentData dataDescription]];
    [_dataCollectedTimeLabel setText:[_currentData createdTime]];
    [_dataUserNameLabel setText:[_currentData createdUserName]];
    [_dataRealNameLabel setText:[_currentData createdRealName]];
    
    _imageArray = [[NSMutableArray alloc] initWithCapacity:10];
    _imageViewArray = [[NSMutableArray alloc] initWithCapacity:10];
    
    _dataNameTextField.delegate = self;
    _dataDescriptionTextField.delegate = self;
    
    [_imageScrollView setContentSize:CGSizeMake(([[_currentData imageList] count]+1) * 96 + ([[_currentData imageList] count])*8, 96)];
    for(int x=0;x<[[_currentData imageList] count];x++){
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[[_currentData imageList] objectAtIndex:x]];
        imageView.userInteractionEnabled = YES;
        [imageView canClickIt:YES];
        
        imageView.frame = CGRectMake(x * (96+8), 0, 96, 96);
        [_imageScrollView addSubview:imageView];
    }
    
    _addImageButton = [[UIButton alloc] initWithFrame:CGRectMake(([[_currentData imageList] count]*104), 0, 96, 96)];
    [_addImageButton setImage:[UIImage imageNamed:@"u189.png"] forState:UIControlStateNormal];
    [_addImageButton addTarget:self action:@selector(addImageButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [_imageScrollView addSubview:_addImageButton];
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [[currentWorkSetManager sharedInstance] updateCollectedData :_currentData :[_currentData name] newName:[_dataNameTextField text] newDescription:[_dataDescriptionTextField text] newImgArray:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshAllCollectedDataOnMapview" object:nil];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)backButonClicked:(id)sender {
    if(_mode == 5){
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        [((UINavigationController*)(self.parentViewController)) popViewControllerAnimated:YES];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"dataDetailViewWillPop" object:nil];
    [super viewWillDisappear:animated];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

-(void)addImageButtonClicked
{
    UzysAssetsPickerController *picker = [[UzysAssetsPickerController alloc] init];
    picker.delegate = self;
    picker.maximumNumberOfSelectionMedia = 5;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"presentMediaPicker" object:picker];
}

- (IBAction)deleteActionClicked:(id)sender {
    if(_mode == 5){
        [[[[currentWorkSetManager sharedInstance] getCurrentWorkSet] collectedDataList] removeObject:_currentData];
        [self dismissViewControllerAnimated:YES completion:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"selectedcollectedDataRemoved" object:nil];
    } else {
        [[[[currentWorkSetManager sharedInstance] getCurrentWorkSet] collectedDataList] removeObjectAtIndex:_index];
        [((UINavigationController*)(self.parentViewController)) popViewControllerAnimated:YES];
    }
    [[currentWorkSetManager sharedInstance] removeCollectedData:[[[currentWorkSetManager sharedInstance] getCurrentWorkSet] name] :_currentData];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"collectedDataRemoved" object:nil];
    
}

- (void)UzysAssetsPickerController:(UzysAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    __weak typeof(self) weakSelf = self;
    __block int totalCount = 0;
    
    if([[assets[0] valueForProperty:@"ALAssetPropertyType"] isEqualToString:@"ALAssetTypePhoto"]) //Photo
    {
        [assets enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            ALAsset *representation = obj;
            
            UIImage *img = [UIImage imageWithCGImage:representation.defaultRepresentation.fullResolutionImage
                                               scale:representation.defaultRepresentation.scale
                                         orientation:(UIImageOrientation)representation.defaultRepresentation.orientation];
            
            if(![weakSelf.imageArray containsObject:img]){
                
                
                [weakSelf.imageArray addObject:img];
                UIImageView *imageView = [[UIImageView alloc] initWithImage:img];
                imageView.userInteractionEnabled = YES;
                [imageView canClickIt:YES];
                
                [weakSelf.imageViewArray addObject:imageView];
                imageView.frame = CGRectMake(idx * (96+8), 0, 96, 96);
                [weakSelf.imageScrollView addSubview:imageView];
                totalCount++;
            }
            *stop = NO;
        }];
        
        CGRect newFrame = weakSelf.addImageButton.frame;
        newFrame.origin.x = totalCount * (96+8);
        weakSelf.addImageButton.frame = newFrame;
        
        [weakSelf.imageScrollView setContentSize:CGSizeMake(([_imageViewArray count]+1) * 96 + [_imageViewArray count] * 8, 96)];
        
        [[currentWorkSetManager sharedInstance] updateCollectedData : weakSelf.currentData :nil newName:[weakSelf.dataNameTextField text] newDescription:nil newImgArray:weakSelf.imageArray];
        
        
    }
    else //Video
    {
        ALAsset *alAsset = assets[0];
        
        UIImage *img = [UIImage imageWithCGImage:alAsset.defaultRepresentation.fullResolutionImage
                                           scale:alAsset.defaultRepresentation.scale
                                     orientation:(UIImageOrientation)alAsset.defaultRepresentation.orientation];
        // weakSelf.imageView.image = img;
        
        
        
        ALAssetRepresentation *representation = alAsset.defaultRepresentation;
        NSURL *movieURL = representation.url;
        NSURL *uploadURL = [NSURL fileURLWithPath:[[NSTemporaryDirectory() stringByAppendingPathComponent:@"test"] stringByAppendingString:@".mp4"]];
        AVAsset *asset      = [AVURLAsset URLAssetWithURL:movieURL options:nil];
        AVAssetExportSession *session =
        [AVAssetExportSession exportSessionWithAsset:asset presetName:AVAssetExportPresetMediumQuality];
        
        session.outputFileType  = AVFileTypeQuickTimeMovie;
        session.outputURL       = uploadURL;
        
        [session exportAsynchronouslyWithCompletionHandler:^{
            
            if (session.status == AVAssetExportSessionStatusCompleted)
            {
                NSLog(@"output Video URL %@",uploadURL);
            }
            
        }];
        
    }
}
- (IBAction)reGatheringButtonClicked:(id)sender {
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"reGatheringSelectedData" object:_currentData];

    
    
}

-(void)showClickedImg:(UITapGestureRecognizer *)sender
{
    
    
}


@end
